package com.chenjun.web.controller.oa;

import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.dao.generator.entity.OaBillLeaveApplication;
import com.chenjun.core.dao.generator.entity.OaDictLeaveType;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.oa.LeaveManagerService;
import com.chenjun.core.service.oa.LeaveTypeManagerService;
import com.chenjun.core.vo.activiti.LeaveDto;
import com.chenjun.web.controller.BaseController;

@SuppressWarnings("serial")
@RequestMapping("/leave")
@Controller
public class LeaveManagerController extends BaseController{
	
	@Resource
	private LeaveManagerService leaveService;
	
	@Resource
	private LeaveTypeManagerService leaveTypeService;
	
	@Resource
	private RuntimeService runtimeService;
	
	@Resource
	private TaskService taskService;
	
	/**
	 * 页面展示
	 * @return
	 * ModelAndView
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("activiti/leave/list");
		DataGridModel dgm = new DataGridModel();
		dgm.setRows(0);
		mv.addObject("types", leaveTypeService.doListByCondition(dgm));
		return mv;
	}
	
	/**
	 * 分页搜索
	 * @param datagrid
	 * @return
	 * ResultDto
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public ResultDto list(DataGridModel datagrid) {
		ResultDto rtDto = new ResultDto();
		datagrid.getSortBy().add(new DataGridSortModel("bill_date", DataGridSortModel.DESC));
		datagrid.getParams().put("emplId", getLoginUserId());
		Pagination data = leaveService.doPagination(datagrid);
		rtDto.setData(data);
		return rtDto;
	}

	/**
	 * 编辑页面元素
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public ResultDto edit(@Valid LeaveDto dto,Errors errors)  throws IllegalAccessException, InvocationTargetException{
		ResultDto rtDto = new ResultDto();
		
		
		//验证
		if (!hanleErrors(rtDto, errors)) { return rtDto; }
		
		SysUser loginUser = getLoginUser();
		OaBillLeaveApplication leave = LeaveDto.getModelByDto(dto);
		OaDictLeaveType leaveType = leaveTypeService.get(leave.getLeaveTypeId());
		Calendar date = Calendar.getInstance();
		leave.setEmplId(loginUser.getId());
		leave.setEmplCode(loginUser.getUserName());
		leave.setEmplName(loginUser.getRealName());
		leave.setStatus(10);
		leave.setLeaveTypeName(leaveType.getName());
		leave.setNo(DateFormatUtils.format(date, "yyyyMMddHHmmss"));
		leave.setBillDate(date.getTime());
		leave.setYear(date.get(Calendar.YEAR));
		leave.setMonth(date.get(Calendar.MONTH) + 1);
		int i = leaveService.createOrUpdate(leave);
		if(i<=0){
			rtDto.resultError();
			rtDto.setMessage("编辑系统异常");
		}
		return rtDto;
	}

	/**
	 * 删除指定的记录
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public ResultDto delete(@PathVariable Integer id) {
		ResultDto rtDto = new ResultDto();
		OaBillLeaveApplication leave = leaveService.get(id);
		int result = 0;
		if (leave != null) {
			result = leaveService.delete(id);
		}
		if (result <= 0) {
			rtDto.resultError();
			rtDto.setMessage("要删除的记录不存在!");
		}
		return rtDto;
	}

	/**
	 * 根据参数获取信息
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/get/{id}")
	@ResponseBody
	public ResultDto get(@PathVariable Integer id) {
		ResultDto rtDto = new ResultDto();
		rtDto.setData(leaveService.get(id));
		return rtDto;
	}
	
	/**
	 * 提交申请
	 */
	@RequestMapping("/apply/{id}")
	@ResponseBody
	public ResultDto submitLeaveApply(@PathVariable Integer id, @RequestParam("leaderships[]") List<String> leaderships){
		ResultDto rtDto = new ResultDto();
		if(leaderships.size() == 0){
			rtDto.resultWaring();
			rtDto.setMessage("请选择审批人");
			return rtDto;
		}
		OaBillLeaveApplication leave = leaveService.get(id);
		Date lbTime = leave.getLeaveBeginTime();
		Date leTime = leave.getLeaveEndTime();
		SysUser loginUser = getLoginUser();
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put("billID", id);
		variables.put("days", daysOfTwo(lbTime, leTime));
		// 设置用户id,用于流程记录发起人
		Authentication.setAuthenticatedUserId(loginUser.getId()); 
		// 启动流程
		ProcessInstance pi = runtimeService.startProcessInstanceByKey("leave", variables);
		// 根据流程实例Id查询任务
		Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); 
		// 指定处理人
		taskService.setVariable(task.getId(), "leaderships", leaderships);
		taskService.setVariable(task.getId(), "positionLevel", loginUser.getPositionLevel());
		// 提交请假单任务
		taskService.complete(task.getId());
		leave.setStatus(20);
		leave.setProcessInstanceId(pi.getProcessInstanceId());
		leaveService.createOrUpdate(leave);
		return rtDto;
	}
	
	public static int daysOfTwo(Date fDate, Date oDate) {

       Calendar aCalendar = Calendar.getInstance();

       aCalendar.setTime(fDate);

       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

       aCalendar.setTime(oDate);

       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

       return day2 - day1;

    }
}
